#include "qtimeproperty.h"

#include <QTimeEdit>

QTimeProperty::QTimeProperty(SHAREDLIB::QAbstractProperty *parent):
    SHAREDLIB::QAbstractProperty(parent)
{
    connect(this,SIGNAL(showValueChanged()),this,SLOT(value_changed()));
}

void QTimeProperty::valueXML(QXmlStreamWriter *w)
{
    QTime ti=getValue().toTime();
    w->writeAttribute("hour",QString::number(ti.hour()));
    w->writeAttribute("minute",QString::number(ti.minute()));
    w->writeAttribute("second",QString::number(ti.second()));
}

void QTimeProperty::parserXML(QXmlStreamReader *r)
{
    QTime ti;
    int hour,minute,second;
    hour=0;
    minute=0;
    second=0;

    foreach(const QXmlStreamAttribute &attribute,r->attributes())
    {
        if(attribute.name().toString()=="hour")
        {
            hour=attribute.value().toString().toInt();
        }
        else if(attribute.name().toString()=="minute")
        {
            minute=attribute.value().toString().toInt();
        }
        else if(attribute.name().toString()=="second")
        {
            second=attribute.value().toString().toInt();
        }
    }

    for(bool finished=false;!finished && !r->hasError();)
    {
        switch(r->readNext())
        {
        case QXmlStreamReader::StartElement:
            break;
        case QXmlStreamReader::EndElement:
            finished=true;
            break;
        default:
            break;
        }
    }

    ti.setHMS(hour,minute,second);
    setValue(ti);
}

QWidget* QTimeProperty::getEditor()
{
    if(attribute("editabled").toBool())
    {
        QTimeEdit *ti=new QTimeEdit;
        connect(ti,SIGNAL(timeChanged(QTime)),this,SLOT(editor(QTime)));
        m_editor=ti;
    }
    return QAbstractProperty::getEditor();
}

void QTimeProperty::editor(const QTime &time)
{
    QTime v=getValue().toTime();
    if(v!=time)
    {
        setModified(true);
        setSignalValue(time);
    }
}

QString QTimeProperty::valueText()
{
    QTime ti=getValue().toTime();
    return QString("%1:%2:%3").arg(ti.hour(),2).arg(ti.minute(),2).arg(ti.second(),2);
}

void QTimeProperty::value_changed()
{
    if(m_editor!=NULL)
    {
        QTimeEdit* ti=(QTimeEdit*)m_editor;
        ti->setTime(m_value.toTime());
    }
}
